import * as vscode from 'vscode';
import { Uri } from 'vscode';
import { CommentAuthorInformation } from 'vscode';
import { HarmonyPilotCommentCollection } from './HarmonyPilotCommentCollection';
import { HarmonyPilotCommentCollectionProvider } from './HarmonyPilotCommentCollectionProvider';
let commentId = 1;

let commentMap = new Map<number, NoteComment>();

class NoteComment implements vscode.Comment {
	id: number;
	label: string | undefined = "this is label";
	public author: CommentAuthorInformation = {
		name: "beichen chang",
		iconPath: Uri.parse("https://cdn.jsdelivr.net/gh/vsls-contrib/code-tour/images/icon-small.png")
	  };
	savedBody: string | vscode.MarkdownString; // for the Cancel button
	constructor(
		public body: string | vscode.MarkdownString,
		public mode: vscode.CommentMode,
		public parent?: vscode.CommentThread,
		public contextValue?: string
	) {
		this.id = ++commentId;
		this.savedBody = this.body;
	}
}

export function activate(context: vscode.ExtensionContext) {

	
	const harmonyPilotCommentCollection = new HarmonyPilotCommentCollection("AI-Review", context, "AI Review");
	harmonyPilotCommentCollection.addComment("## 这是一条注释1"
		, "/home/changbeichen/code/vscode-extension-samples/webview-view-sample/media/main.css", 
		new vscode.Position(22, 0), new vscode.Position(23, 1), ".color-preview:nohover {", "this is a label");
	
	harmonyPilotCommentCollection.addComment("## 这是一条注释2"
		, "/home/changbeichen/code/vscode-extension-samples/webview-view-sample/media/main.css", 
		new vscode.Position(21, 0), new vscode.Position(23, 1), ".color-preview:nohover {", "this is a label");
		
	// 注册跳转到下一个评论的命令
	context.subscriptions.push(vscode.commands.registerCommand('harmonypilot.applyAndGoToNext', (threadUuid: string) => {
		const collection = HarmonyPilotCommentCollectionProvider.getCollection(threadUuid);
		if (collection == undefined) {
			return;
		}
		collection.applyAndGoToNext(threadUuid);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('harmonypilot.discardAndGoToNext', (threadUuid: string) => {
		const collection = HarmonyPilotCommentCollectionProvider.getCollection(threadUuid);
		if (collection == undefined) {
			return;
		}
		collection.discardAndGoToNext(threadUuid);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('harmonypilot.goToNextByTitle', (thread: vscode.CommentThread) => {
		const uuid = HarmonyPilotCommentCollectionProvider.getUuidByThread(thread);
		if (uuid == undefined) {
			return;
		}
		const collection = HarmonyPilotCommentCollectionProvider.getCollection(uuid);
		if (collection == undefined) {
			return;
		}
		collection.goToNextComment(uuid);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('harmonypilot.goToPreviousByTitle', (thread: vscode.CommentThread) => {
		const uuid = HarmonyPilotCommentCollectionProvider.getUuidByThread(thread);
		if (uuid == undefined) {
			return;
		}
		const collection = HarmonyPilotCommentCollectionProvider.getCollection(uuid);
		if (collection == undefined) {
			return;
		}
		collection.goToPreviousComment(uuid);
	}));
}

export function activate1(context: vscode.ExtensionContext) {
	// A `CommentController` is able to provide comments for documents.
	const commentController = vscode.comments.createCommentController('comment-sample', 'Comment API Sample');
	const commentController2 = vscode.comments.createCommentController('comment-sample2', 'Comment API Sample2');
	context.subscriptions.push(commentController);
	context.subscriptions.push(commentController2);

	// A `CommentingRangeProvider` controls where gutter decorations that allow adding comments are shown
	// commentController.commentingRangeProvider = {
	// 	provideCommentingRanges: (document: vscode.TextDocument, _token: vscode.CancellationToken) => {
	// 		const lineCount = document.lineCount;
	// 		return [new vscode.Range(0, 0, lineCount - 1, 0)];
	// 	}
	// };

	const thread = commentController.createCommentThread(
		vscode.Uri.file('/home/changbeichen/code/vscode-extension-samples/webview-view-sample/media/main.css'), // 固定的本地文件URI
		new vscode.Range(21, 0, 21, 22), // 第二行的range
		[] // Start with empty comments array
	);

	const thread2 = commentController2.createCommentThread(
		vscode.Uri.file('/home/changbeichen/code/vscode-extension-samples/webview-view-sample/media/reset.css'), // 固定的本地文件URI
		new vscode.Range(9, 0, 9, 0), // 第二行的range
		[] // Start with empty comments array
	);


	thread.canReply = false;
	thread2.canReply = false;

	// Set thread properties
	thread.collapsibleState = vscode.CommentThreadCollapsibleState.Expanded;
	
	// Create a new comment
	const comment = new NoteComment(
		new vscode.MarkdownString(`## 这是一条注释\n\n---\n`),
		vscode.CommentMode.Preview,
		thread,
		undefined
	);
	
	const comment2 = new NoteComment(
		new vscode.MarkdownString(`## 这是一条注释\n\n---\n`),
		vscode.CommentMode.Preview,
		thread,
		undefined
	);

	// Add the comment to the thread
	thread.comments = [comment];
	thread2.comments = [comment2];

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.createNote', (reply: vscode.CommentReply) => {
		replyNote(reply);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.replyNote', (reply: vscode.CommentReply) => {
		replyNote(reply);
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.startDraft', (reply: vscode.CommentReply) => {
		const thread = reply.thread;
		thread.contextValue = 'draft';
		const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, thread);
		newComment.label = 'pending';
		thread.comments = [...thread.comments, newComment];
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.finishDraft', (reply: vscode.CommentReply) => {
		const thread = reply.thread;

		if (!thread) {
			return;
		}

		thread.contextValue = undefined;
		thread.collapsibleState = vscode.CommentThreadCollapsibleState.Collapsed;
		if (reply.text) {
			const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, thread);
			thread.comments = [...thread.comments, newComment].map(comment => {
				comment.label = undefined;
				return comment;
			});
		}
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.deleteNoteComment', (comment: NoteComment) => {
		const thread = comment.parent;
		if (!thread) {
			return;
		}

		thread.comments = thread.comments.filter(cmt => (cmt as NoteComment).id !== comment.id);

		if (thread.comments.length === 0) {
			thread.dispose();
		}
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.deleteNoteComment2', (commentId: number) => {
		console.log('Deleting comment with ID:', commentId);
		const comment = commentMap.get(commentId);
		if (!comment) {
			console.log('Comment not found with ID:', commentId);
			return;
		}

		const thread = comment.parent;
		if (!thread) {
			return;
		}
		
		// 删除前从映射中移除
		commentMap.delete(comment.id);

		thread.comments = thread.comments.filter(cmt => (cmt as NoteComment).id !== comment.id);

		if (thread.comments.length === 0) {
			thread.dispose();
		}
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.deleteNote', (thread: vscode.CommentThread) => {
		thread.dispose();
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.cancelsaveNote', (comment: NoteComment) => {
		if (!comment.parent) {
			return;
		}

		comment.parent.comments = comment.parent.comments.map(cmt => {
			if ((cmt as NoteComment).id === comment.id) {
				cmt.body = (cmt as NoteComment).savedBody;
				cmt.mode = vscode.CommentMode.Preview;
			}

			return cmt;
		});
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.saveNote', (comment: NoteComment) => {
		if (!comment.parent) {
			return;
		}

		comment.parent.comments = comment.parent.comments.map(cmt => {
			if ((cmt as NoteComment).id === comment.id) {
				(cmt as NoteComment).savedBody = cmt.body;
				cmt.mode = vscode.CommentMode.Preview;
			}

			return cmt;
		});
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.editNote', (comment: NoteComment) => {
		if (!comment.parent) {
			return;
		}

		comment.parent.comments = comment.parent.comments.map(cmt => {
			if ((cmt as NoteComment).id === comment.id) {
				cmt.mode = vscode.CommentMode.Editing;
			}

			return cmt;
		});
	}));

	context.subscriptions.push(vscode.commands.registerCommand('mywiki.dispose', () => {
		commentController.dispose();
	}));

	function replyNote(reply: vscode.CommentReply) {
		const thread = reply.thread;
		thread.canReply = false;

		let content = reply.text;
	
		content += "\n\n---\n"

		let body = new vscode.MarkdownString(content);
		body.isTrusted = true;

		const newComment = new NoteComment(body, vscode.CommentMode.Preview, thread, thread.comments.length ? 'canDelete' : undefined);
		
		commentMap.set(newComment.id, newComment);
		
		body.appendMarkdown(`[Delete](command:mywiki.deleteNoteComment2?${encodeURIComponent(JSON.stringify(newComment.id))})`);

		if (thread.contextValue === 'draft') {
			newComment.label = 'pending';
		}

		thread.comments = [...thread.comments, newComment];
	}
}
